package org.microsites.domain.dao.eod;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.Select;
import net.lemnik.eodsql.Update;

import org.microsites.domain.dao.LockDAO;
import org.microsites.domain.model.Lock;
import org.microsites.domain.model.User;
import org.microsites.util.EodDaoSupport;

public class LockDAOImpl extends EodDaoSupport implements LockDAO {
	private Query query;
	
	public Query getQuery() {
		return query == null ? query = super.getQuery(Query.class) : query;
	}

	@Override
	public void create(Lock l) {
		getQuery().create(l);
	}

	@Override
	public void delete(String key) {
		getQuery().delete(key);
	}

	@Override
	public Lock load(String key) {
		return getQuery().load(key);
	}

	@Override
	public Lock load(String key, Long user) {
		return getQuery().load(key, user);
	}

	@Override
	public void update(Lock l) {
		getQuery().update(l);
	}

	@Override
	public void wipe(Long timestamp) {
		getQuery().wipe(timestamp);
	}

	@Override
	public void wipe(User user) {
		getQuery().wipe4user(user.getId());
	}

	static interface Query extends BaseQuery {

		@Select(sql = "SELECT * FROM [Lock] WHERE [key]=?1 and [user]=?2")
		public Lock load(String key, Long user);

		@Select(sql = "SELECT * FROM [Lock] WHERE [key]=?1")
		public Lock load(String key);

        @Update(sql = "INSERT INTO [Lock] ([key],[timestamp],[user],pending) VALUES (?{1.key},?{1.timestamp},?{1.user},?{1.pending})")
		public void create(Lock l);
		
        @Update(sql = "UPDATE [Lock] SET [timestamp]=?{1.timestamp},[user]=?{1.user},[pending]=?{1.pending} WHERE [key]=?{1.key}")
		public void update(Lock l);
		
		@Update(sql = "DELETE FROM [Lock] WHERE [key]=?1")
		public void delete(String key);

		@Update(sql = "DELETE FROM [Lock] WHERE [timestamp]<?1")
		public void wipe(Long timestamp);

		@Update(sql = "DELETE FROM [Lock] WHERE [user]=?1")
		public void wipe4user(Long user);
	}
	
}
